#include <string.h>
#include <stdlib.h>
#include "hash.h"


int bucketNum = 0;
static int hash_func(int key){
	return key % HSIZE;
}

struct hashTable * ssb_create_hash_table(void){
	struct hashTable * ht = (struct hashTable *)malloc(sizeof(struct hashTable));
	memset(ht,0,sizeof(struct hashTable));
	bucketNum = 0;
	return ht;
}

void ssb_destroy_hash_table(struct hashTable * ht){
	free(ht);
}

void * ssb_get_hash_table(struct hashTable *ht,int key){
	int hkey = hash_func(key);
	int offset = 0;
	struct tuple *tmp;

	if(ht->num[hkey] == 0)
		return NULL;
	else{
		while(offset<ht->num[hkey]){
			tmp = (struct tuple *)(ht->bucket[hkey] + sizeof(struct tuple)*offset);
			offset ++;
			if(tmp->key == key)
				return tmp;
		}
		return NULL;
	}
}

void ssb_insert_hash_table(struct hashTable *ht,int key,void *value, int value_size){
	int hkey = hash_func(key);
	bucketNum ++;
	ht->num[hkey]++;
	if(ht->num[hkey] == 1){
		ht->bucket[hkey] = (char *) malloc(ASIZE * value_size);
	}else if (ht->num[hkey] % ASIZE == 0){
		ht->bucket[hkey] = (char *) realloc(ht->bucket[hkey],(ht->num[hkey]+ASIZE)*value_size);
	}
	memcpy(ht->bucket[hkey] + (ht->num[hkey]-1)*value_size,value,value_size);
}


int ssb_size_hash_table(struct hashTable *ht){
	return sizeof(struct hashTable);
}

int ssb_bucket_size_hash_table(){
	return bucketNum*sizeof(struct tuple);
}
